package org.jeecg.modules.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.bouncycastle.jcajce.provider.digest.Tiger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.json.JSONTokener;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.device.*;
import org.jeecg.modules.entity.TigDevice;
import org.jeecg.modules.entity.TigDeviceTcpLog;
import org.jeecg.modules.entity.TigerDeviceLog;
import org.jeecg.modules.message.DeviceListWebSocket;
import org.jeecg.modules.message.DeviceWebSocket;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.service.ITigDeviceService;
import org.jeecg.modules.driver.DriverCommandList;
import org.jeecg.modules.service.ITigDeviceTcpLogService;
import org.jeecg.modules.service.ITigerDeviceLogService;
import org.jeecg.modules.util.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    DeviceContainer deviceContainer;

    @Autowired
    ITigDeviceService iTigDeviceService;

    @Autowired
    ITigDeviceTcpLogService iTigDeviceTcpLogService;

    @Autowired
    ITigerDeviceLogService iTigDeviceLogService;

    @Autowired
    DeviceWebSocket deviceWebSocket;

    @Autowired
    DeviceListWebSocket deviceListWebSocket;

    @Autowired
    ITigerDeviceLogService iTigerDeviceLogService;

    @Autowired
    ISysBaseAPI sysBaseApi;

//    @Autowired
//    RabbitMqClient rabbitMqClient;

    /**
     * Reload From Database, refresh infomation
     *
     * @param deviceId
     */
    public Boolean reloadDevice(String deviceId) {
        try {
            TigDevice d = iTigDeviceService.getById(deviceId);
            if(d == null){
                //证明已经在数据库被删除了
                return false;
            }
            JSONObject jo = ConvertUtil.toJsonTigDevice(d);
            saveDeviceToRedis(d.getId(), jo);
//            //替换了redis后需要重新获取device更新现有内存中的设备信息
            //           saveDevice(getDevice(deviceId)); 不能放这里，getdevice那里用了reloadDevice，容易造成死循环
            return  true;
        } catch (Exception e) {
            log.error("fail to reload device to shadow", e);
            return false;
        }
    }

    @Override
    public Device getDevice(String deviceId) {
        try {
            //先获取redis上面的，没有再reload
            Object obj = redisUtil.get("tig_shadow_" + deviceId);
            if (obj == null) {
                if(reloadDevice(deviceId))
                    return getDevice(deviceId);
                else
                    return null;
            }
            JSONObject jsonD = (JSONObject) obj;
            Device d;
            d = new PowerDevice();
            d.setShadow(jsonD);
            d.setId(jsonD.getString("id"));
            d.setIpAddr(jsonD.getJSONObject("network").getString("ip"));
            d.setPort(jsonD.getJSONObject("network").getString("port"));
            d.setOnStatus(jsonD.getJSONObject("baseinfo").getString("isOnline"));
            d.setIson(jsonD.getJSONObject("baseinfo").getString("isActive"));
            TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
            if (sd != null)
                d.setDeviceDriver(sd.getDevice().getDeviceDriver());
            return d;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public TigDevice getTigDevice(String deviceId) {
        TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
        if (sd != null) {
            return sd.getTigDeviceEntity();
        }
        return null;
    }


    /**
     * Login device, refresh from redis first
     */
    @Override
    public boolean login(String deviceId, Boolean isManual) {
        Device device = getDevice(deviceId);
        //如果已经连接中，先断开连接.
        if (device.getIsManualDisconnect()) {
            //通过手动断开的只有手动链接才能触发
            if (!isManual)
                return true;
        }
        TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
        if (sd != null) {
            disconnect(deviceId, false);
        }
        sd = deviceContainer.createDeviceShadow(device);
        device.online(isManual);
        //check whether device create success
        if (sd == null) {
            //用来断开ip和端口本来就不连通的链接。
            disconnect(deviceId, false);
            return false;
        }
        TigDevice td = iTigDeviceService.getById(deviceId);
        sd.setTigDeviceEntity(td);
        log.info("连接设备:" + device.getIpAddr() + ":" + device.getPort());
        return sd.getDevice().login();
    }

    @Override
    public void saveDevice(Device device) {
        TigDevice d = iTigDeviceService.getById(device.getId());
        try {
            long on = 0, off = 0;
            if (device.getShadow().has("onTime"))
                on = device.getShadow().getLong("onTime");
            if (device.getShadow().has("offTime"))
                off = device.getShadow().getLong("offTime");
            d.setOnStatus(Integer.parseInt(device.getShadow().getJSONObject("baseinfo").getString("isOnline")));
            if (on != 0)
                d.setOnTime(new Date(on));
            if (off != 0)
                d.setOffTime(new Date(off));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        d.setShadowName(device.getShadow().toString());
        saveDeviceToRedis(d.getId(), device.getShadow());
        iTigDeviceService.updateById(d);
        TigDeviceShadow sd = deviceContainer.getShadowDevice(device.getId());
        if (sd != null) {
            if (sd.getDevice() == null)//直接设置device会有机会替换掉原来的device，然后驱动程序乱了
                sd.setDevice(device);
            else
                sd.getDevice().setShadow(device.getShadow());
            sd.setTigDeviceEntity(d);
        }
    }

    public void saveDevice(String deviceId) {
        TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
        saveDevice(sd.getDevice());
    }

    @Override
    public boolean disconnect(String deviceId, Boolean isManual) {
        TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
        if (sd != null) {
            sd.disConnect();
            sd.getDevice().offLine(isManual);
            saveDevice(sd.getDevice());
            deviceWebSocket.pushMessage(deviceId, sd.getDevice().getShadow().toString());
            deviceListWebSocket.pushMessage(deviceId, sd.getDevice().getShadow().toString());
            deviceContainer.removeDevice(sd);
        } else {
            //Set device to disconnected satus
            Device d = getDevice(deviceId);
            d.offLine(isManual);
            saveDevice(d);
            deviceWebSocket.pushMessage(deviceId, d.getShadow().toString());
            deviceListWebSocket.pushMessage(deviceId, d.getShadow().toString());
            //updateDeviceOnlineStatus(deviceId, 0);
            //sendLocal(deviceId, DriverCommandList.D_LOCAL_DISCONNECT + "##1");
        }

        //TODO:更新数据库状态
        return true;
    }

    @Override
    public boolean removeDevice(String deviceId) {
        disconnect(deviceId, false);
        removeDeviceToRedis(deviceId);
        return false;
    }
//
//    @Override
//    public void sendLocal(String deviceId, String msg){
//        if(rabbitMqClient != null){
//            BaseMap bm = new BaseMap();
//            bm.put("deviceId",deviceId);
//            bm.put("data",msg);
//            rabbitMqClient.sendMessage("devicedata",bm);
//        }
//    }

    @Override
    public boolean runCommand(String cmd, JSONObject deviceData) {
        try {
            String deviceId = deviceData.getString("id");
            BaseMap map = new BaseMap();
            map.put("deviceId", deviceId);
            map.put("cmd", cmd);
            map.put("data", deviceData.toString());

            try {
                if (deviceId != null) {
                    log.info("command:" + cmd);
                    TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
                    if (sd == null) {
                        return false;
                    }
                    if (cmd.equals(DriverCommandList.SET_DEVICE_LOCAL_DATA)) {
                        saveSwitchesLogs(sd, deviceData);
                        Device dev = sd.getDevice();
                        JSONObject shadow = dev.getShadow();
                        JSONObject jsw = deviceData.getJSONObject("switches");
                        shadow.put("switches", jsw);
                        dev.setShadow(shadow);
                        saveDevice(dev);
//                        TigDevice tigDev = iTigDeviceService.getById(deviceId);
//                        JSONObject jo = ConvertUtil.toJsonTigDevice(tigDev);
//                        JSONObject jsw = deviceData.getJSONObject("switches");
//                        jo.put("switches",jsw);
//                        String shadowName = jo.toString();
//                        //log.info("shadowName:" +shadowName);
//                        tigDev.setShadowName(shadowName);
//                        iTigDeviceService.updateById(tigDev);
//                        reloadDevice(tigDev.getId());

//                        JSONArray jsonSwitches = deviceData.getJSONObject("switches").getJSONArray("switches");
//                        for (int i = 0; i < jsonSwitches.length(); i++) {
//                            String switchName = jsonSwitches.getJSONObject(i).getString("name");
//                            JSONArray devSwitches = sd.getDevice().getShadow().getJSONObject("switches").getJSONArray("switches");
//                            devSwitches.getJSONObject(i).put("name",switchName);
//                        }
                    }
                    if (cmd.equals((DriverCommandList.SET_DEVICE_CONFIG))) {
                        Device dev = sd.getDevice();
                        if (dev.getDeviceDriver().runCommand(cmd, deviceData)) {
                            saveBaseInfoLogs(sd, deviceData);
//                            JSONObject shadow = dev.getShadow();
//                            JSONObject jbaseinfo = deviceData.getJSONObject("baseinfo");
//                            saveBaseInfoLogs(sd,deviceData);
//                            shadow.put("baseinfo", jbaseinfo);
//                            dev.setShadow(shadow);
//                            saveDevice(dev);
                            saveDeviceDataLog(sd, cmd, deviceData.toString());
                        }
                    }
                    if (cmd.equals((DriverCommandList.SET_DEVICE_CHANNEL_SWITCH)) || cmd.equals((DriverCommandList.SET_DEVICE_CHANNEL_CURRENT))) {
                        if (sd.getDevice().getDeviceDriver().runCommand(cmd, deviceData)) {
                            saveSwitchesLogs(sd, deviceData);
                            saveDeviceDataLog(sd, cmd, deviceData.toString());
                        }
                    } else {
                        sd.getDevice().getDeviceDriver().runCommand(cmd, deviceData);
                        saveDeviceDataLog(sd, cmd, deviceData.toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void saveDeviceToRedis(String deviceId, JSONObject jo) {
        redisUtil.set("tig_shadow_" + deviceId, jo);
    }

    private void removeDeviceToRedis(String deviceId) {
        redisUtil.del("tig_shadow_" + deviceId);
    }

    /**
     * 在线设备设置离线
     */
    @Override
    public void resetDeviceState() {
        LambdaUpdateChainWrapper<TigDevice> wrapper = iTigDeviceService.lambdaUpdate();
        wrapper.set(TigDevice::getOnStatus, 0);
        wrapper.set(TigDevice::getOffTime, Calendar.getInstance().getTime());
        wrapper.eq(TigDevice::getOnStatus, 1);
        wrapper.update();
    }

    /**
     * 或者所有激活设备，最近上线排序
     */
    @Override
    public List<TigDevice> getActiveDevices() {
        LambdaQueryWrapper<TigDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TigDevice::getIson, 1);
        wrapper.eq(TigDevice::getOnStatus, 0);
        wrapper.orderByDesc(TigDevice::getOffTime);
        return iTigDeviceService.list(wrapper);
    }

    /**
     * 或者所有激活设备，最近上线排序
     */
    @Override
    public List<TigDevice> getDevices() {
        LambdaQueryWrapper<TigDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TigDevice::getIson, 1);
        wrapper.orderByDesc(TigDevice::getCreateTime);
        return iTigDeviceService.list(wrapper);
    }

    @Override
    public int getDevicesCount(String org_code) {
        LambdaQueryWrapper<TigDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(TigDevice::getSysOrgCode, org_code);
        return iTigDeviceService.list(wrapper).size();
    }

    @Override
    public int getOnlineDevicesCount(String org_code) {
        LambdaQueryWrapper<TigDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TigDevice::getOnStatus, 1);
        wrapper.like(TigDevice::getSysOrgCode, org_code);
        return iTigDeviceService.list(wrapper).size();
    }

    @Override
    public int getOfflineDevicesCount(String org_code) {
        LambdaQueryWrapper<TigDevice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TigDevice::getOnStatus, 0);
        wrapper.eq(TigDevice::getIson, 1);
        wrapper.like(TigDevice::getSysOrgCode, org_code);
        return iTigDeviceService.list(wrapper).size();
    }

    /**
     * 根据机构代码和警告代码查询警告次数
     *
     * @param orgCode  机构码
     * @param warnType 异常码 -1所有异常 1市电异常、2主电压异常、3备电压异常、4电流异常、5ups异常、6温度异常、7通道异常
     * @param date
     * @return
     */
    @Override
    public int getWarningCount(String orgCode, int warnType, LocalDate date) {
        LambdaQueryWrapper<TigerDeviceLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(TigerDeviceLog::getSysOrgCode, orgCode);
        wrapper.ge(TigerDeviceLog::getCreateTime, date);
        if (warnType == -1)
            wrapper.eq(TigerDeviceLog::getLogCategory, 1);
        else
            wrapper.eq(TigerDeviceLog::getLogType, warnType);
        return iTigDeviceLogService.list(wrapper).size();
    }

    @Override
    public int getWarningCountByDeviceId(String id, int warnType) {
        LambdaQueryWrapper<TigerDeviceLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TigerDeviceLog::getDeviceId, id);
        if (warnType == -1)
            wrapper.eq(TigerDeviceLog::getLogCategory, 1);
        else
            wrapper.eq(TigerDeviceLog::getLogType, warnType);
        return iTigDeviceLogService.list(wrapper).size();
    }

    @Override
    public void generateDeviceOperateLog(String deviceId, String warningType, String warningMsg) throws Exception {
        Device d = getDevice(deviceId);
        TigerDeviceLog log = new TigerDeviceLog();
        Date date = new Date();

        log.setName(d.getShadow().getJSONObject("baseinfo").getString("name"));
        log.setDeviceId(d.getId());
        log.setLogTime(date);
        log.setContent(warningMsg);
        log.setLogCategory("2");//操作类型
        //log.setHandleStatus("2");//已上报
        log.setOperateType(warningType);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        log.setUpdateBy(user.getRealname());
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String transformDate = simpleDateFormat.format(date);
        log.setUpdateTime(date);
        log.setSysOrgCode(iTigDeviceService.getById(deviceId).getSysOrgCode());
        iTigerDeviceLogService.save(log);


//        //redis设备错误类型计数
//        int typeCount = 0;
//        if(redisUtil.get("device_warning_" + warningType + "type" + d.getId()) != null){
//            typeCount = Integer.parseInt(String.valueOf(redisUtil.get("device_warning_" + warningType + "type" + d.getId())));
//            typeCount++;
//        }
//        else {
//            typeCount =deviceService.getWarningCountByDeviceId(d.getId(),Integer.parseInt(warningType));
//        }
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String transformDate = simpleDateFormat.format(date);
//        redisUtil.set("device_warning_time"+d.getId(),transformDate);
//        redisUtil.set("device_warning_" + warningType + "type" + d.getId(),typeCount);
    }

    @Override
    public void sendAnnouncementToDepartment(String deviceId, String name,String msg) throws Exception {
        //----------------推送系统消息--------------------------------------------
        TigDevice tDev = getTigDevice(deviceId);
        String departId = sysBaseApi.getDepartIdsByOrgCode(tDev.getSysOrgCode());
        while (departId != null && departId.compareTo("") != 0) {
            List<String> uIds = sysBaseApi.getDeptHeadByDepId(departId);
            for (String uid : uIds) {
                MessageDTO md = new MessageDTO();
                md.setToAll(true);
                md.setTitle(name);
                md.setFromUser("admin");
                md.setToUser(uid);
                md.setToAll(false);
                md.setContent(msg);
                md.setCategory(CommonConstant.MSG_CATEGORY_2);
                sysBaseApi.sendSysAnnouncement(md);
            }
            //sysBaseApi.sendWebSocketMsg(uIds.toArray(new String[]{}),msg);
            DictModel dictModel = sysBaseApi.getParentDepartId(departId);
            departId = dictModel.getText();
        }
    }


    private void saveDeviceDataLog(TigDeviceShadow sd, String command, String content) throws Exception {
        //暂时屏蔽
//        TigDeviceTcpLog log = new TigDeviceTcpLog();
//        log.setDeviceName(sd.getDevice().getShadow().getJSONObject("baseinfo").getString("name"));
//        log.setDeviceId(sd.getDevice().getId());
//        log.setContent(content);
//        log.setCommand(command);
//        log.setDirection("下发");
//        iTigDeviceTcpLogService.save(log);
    }

    private void saveBaseInfoLogs(TigDeviceShadow sd, JSONObject deviceData) throws Exception {
        Device dev = sd.getDevice();
        JSONObject shadow = dev.getShadow();
        JSONObject jbaseinfo = deviceData.getJSONObject("baseinfo");
        JSONObject joldbaseinfo = shadow.getJSONObject("baseinfo");
        String logMsg = "修改了设备【" + sd.getTigDeviceEntity().getName() + "】预警信息：";
        if (jbaseinfo.getString("mainVolMax").compareTo(joldbaseinfo.getString("mainVolMax")) != 0)
            logMsg += "主电电压最大值修改：【" + joldbaseinfo.getString("mainVolMax") + " -> " + jbaseinfo.getString("mainVolMax") + "】\n";
        if (jbaseinfo.getString("mainVolMin").compareTo(joldbaseinfo.getString("mainVolMin")) != 0)
            logMsg += "主电电压最小值修改：【" + joldbaseinfo.getString("mainVolMin") + " -> " + jbaseinfo.getString("mainVolMin") + "】\n";
        if (jbaseinfo.getString("backVolMax").compareTo(joldbaseinfo.getString("backVolMax")) != 0)
            logMsg += "备电电压最大值修改：【" + joldbaseinfo.getString("backVolMax") + " -> " + jbaseinfo.getString("backVolMax") + "】\n";
        if (jbaseinfo.getString("backVolMin").compareTo(joldbaseinfo.getString("backVolMin")) != 0)
            logMsg += "备电电压最小值修改：【" + joldbaseinfo.getString("backVolMin") + " -> " + jbaseinfo.getString("backVolMin") + "】\n";
        if (jbaseinfo.getString("mainCurMax").compareTo(joldbaseinfo.getString("mainCurMax")) != 0)
            logMsg += "主电流最大值修改：【" + joldbaseinfo.getString("mainCurMax") + " -> " + jbaseinfo.getString("mainCurMax") + "】\n";
        if (jbaseinfo.getString("fanTempMax").compareTo(joldbaseinfo.getString("fanTempMax")) != 0)
            logMsg += "开启风扇温度值修改：【" + joldbaseinfo.getString("fanTempMax") + " -> " + jbaseinfo.getString("fanTempMax") + "】\n";
        if (jbaseinfo.getString("tempMax").compareTo(joldbaseinfo.getString("tempMax")) != 0)
            logMsg += "预警温度修改：【" + joldbaseinfo.getString("tempMax") + " -> " + jbaseinfo.getString("tempMax") + "】\n";
        //对比
        generateDeviceOperateLog(dev.getId(), "203", logMsg);
    }

    private void saveSwitchesLogs(TigDeviceShadow sd, JSONObject deviceData) throws Exception {
        Device dev = sd.getDevice();
        JSONObject shadow = dev.getShadow();
        JSONArray oldArrData = shadow.getJSONObject("switches").getJSONArray("switches");
        JSONArray arrData = deviceData.getJSONObject("switches").getJSONArray("switches");
        String logMsg = "修改了设备【" + sd.getTigDeviceEntity().getName() + "】通道信息：";
        for (int i = 0; i < arrData.length(); i++) {
            JSONObject oldObj = oldArrData.getJSONObject(i);
            JSONObject obj = arrData.getJSONObject(i);
            String msg = "通道" + (i + 1) + "修改:";
            boolean bChange = false;
            if (obj.getString("name").compareTo(oldObj.getString("name")) != 0) {
                msg += "名字【" + oldObj.getString("name") + " -> " + obj.getString("name") + "】\n";
                bChange = true;
            }
            if (obj.getString("state").compareTo(oldObj.getString("state")) != 0) {
                msg += "通道【" + ConvertUtil.toSwitchState(oldObj.getString("state")) + " -> " + ConvertUtil.toSwitchState(obj.getString("state")) + "】\n";
                bChange = true;
            }
            if (obj.getString("controlC").compareTo(oldObj.getString("controlC")) != 0) {
                msg += "通道电流控制值【" + oldObj.getString("controlC") + " -> " + obj.getString("controlC") + "】\n";
                bChange = true;
            }
            if (bChange)
                logMsg += msg + '\n';
        }
        generateDeviceOperateLog(dev.getId(), "204", logMsg);
    }

    public void saveBaseDeviceLog(TigDevice newTigDevice) throws Exception {
        TigDevice curTigDevice = getTigDevice(newTigDevice.getId());
        String logMsg = "修改了设备【" + curTigDevice.getName() + "】基础信息：\n";
        if (curTigDevice.getName().compareTo(newTigDevice.getName()) != 0)
            logMsg += "【名字：" + curTigDevice.getName() + " -> " + newTigDevice.getName() + "】\n";
        if (curTigDevice.getIpAddr().compareTo(newTigDevice.getIpAddr()) != 0)
            logMsg += "【IP：" + curTigDevice.getIpAddr() + " -> " + newTigDevice.getIpAddr() + "】\n";
        if (curTigDevice.getPort().compareTo(newTigDevice.getPort()) != 0)
            logMsg += "【端口：" + curTigDevice.getPort() + " -> " + newTigDevice.getPort() + "】\n";
        if (curTigDevice.getOnStatus() != newTigDevice.getOnStatus())
            logMsg += "【在线状态：" + ConvertUtil.toOnlineState(curTigDevice.getOnStatus()) + " -> " + ConvertUtil.toOnlineState(newTigDevice.getOnStatus()) + "】\n";
        if (curTigDevice.getIson() != newTigDevice.getIson())
            logMsg += "【激活状态：" + ConvertUtil.toActiveState(curTigDevice.getIson()) + " -> " + ConvertUtil.toActiveState(newTigDevice.getIson()) + "】\n";
        generateDeviceOperateLog(newTigDevice.getId(), "203", logMsg);
    }

    @Override
    public Boolean isExistSameDevice(TigDevice tigDevice) {
        List<TigDevice> listDevs = getDevices();
        for (TigDevice tDev : listDevs) {
            //编辑设备的时候
            if (tigDevice.getId() != null) {
                if (tDev.getId().compareTo(tigDevice.getId()) != 0 && ((tDev.getIpAddr().compareTo(tigDevice.getIpAddr()) == 0 &&
                        tDev.getPort().compareTo(tigDevice.getPort()) == 0) ||
                        (tDev.getName().compareTo(tigDevice.getName()) == 0))) {
                    return true;
                }
            } else {//新增设备的时候
                if ((tDev.getIpAddr().compareTo(tigDevice.getIpAddr()) == 0 &&
                        tDev.getPort().compareTo(tigDevice.getPort()) == 0) ||
                        tDev.getName().compareTo(tigDevice.getName()) == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Boolean isExistDevicesByOrgCode(String orgCode) {
        List<TigDevice> listDevs = getDevices();
        for (TigDevice tDev : listDevs) {
            if (tDev.getSysOrgCode().contains(orgCode)) {
                return true;
            }
        }
        return false;
    }
}
